import os
import json
import time
import subprocess
from utils import Logger, DeviceMode, UpgradeTool
from constants import *


class BuildFlashHandler():
    def __init__(self, code_path: str) -> None:
        self.code_path = code_path
        self.cd_path = f"cd {self.code_path}"

    def _clean_and_update(self):
        # 代码清理更新
        Logger.info(f"remove files: {REMOVE_FILES}")
        os.system(f"{self.cd_path} && {REMOVE_FILES}")
        Logger.info(f"repo clean: {REPO_CLEAN}")
        os.system(f"{self.cd_path} && {REPO_CLEAN}")
        Logger.info(f"repo update: {REPO_UPDATE}")
        os.system(f"{self.cd_path} && {REPO_UPDATE}")
        Logger.info(f"build before: {BUILD_BEFORE}")
        os.system(f"{self.cd_path} && {BUILD_BEFORE}")

    def _check_images(self, image_path, part_list):
        # 检查所有的镜像是否正常
        all_exist = True
        for filename in part_list:
            filepath = os.path.join(image_path, filename)
            if not os.path.exists(filepath+".img"):
                Logger.info(f"Image '{filename}' does not exist.")
                all_exist = False
        if all_exist:
            Logger.info("All images exist.")
        return all_exist

    def _build_image(self):
        # 编译镜像
        Logger.info("build image start")
        build_image = f"{self.cd_path} && {BUILD_IMAGE}"
        os.system(build_image)
        Logger.info("build image end")

    def _flash_image(self):
        Logger.info("flash image start")
        image_path = self.code_path + "/out/rk3568/packages/phone/images"
        parts = ['uboot', 'resource', 'boot_linux', 'ramdisk',
                 'system', 'vendor', 'sys_prod', 'chip_prod',
                 'updater', 'eng_system', 'chip_ckm', 'userdata']
        result = self._check_images(image_path, parts)
        if result:
            os.system("hdc shell reboot loader")
            time.sleep(10)
            tool = UpgradeTool(image_path)
            tool.flash_loader()
            tool.flash_parameter()
            for part in parts:
                tool.flash_one(part)
            tool.flash_reboot()
            Logger.info("flash image successfully")
        else:
            Logger.error("flas image failed")

    def _build_tests(self):
        """
        编译所有测试套
        """
        Logger.info("build test start")
        build_test = f"{self.cd_path} && {BUILD_TEST}"
        text = os.system(build_test)
        Logger.info("build test end")

    def process(self):
        self._clean_and_update()
        self._build_image()
        self._flash_image()
        self._build_tests()
